import {
	login,
	getUserImg,
	getUserInfo,
	getCosSecret,
	setDefaultPhoneModel
} from '@/api/user.js'
import {
	paymentOrder
} from '@/api/product.js'
import store from '@/store/store.js'
import config from '@/config.js'
import {
	mapGetters,
	mapMutations
} from 'vuex'
import WebSocket from "@/utils/websocket4.js"

// 在文件顶部添加状态锁
let isLogging = false; // 定义一个状态锁，初始值为false

export const resolution = () =>{
	const systemInfo = uni.getSystemInfoSync();
	return systemInfo // 直接返回系统信息对象
}

export const userLogin = async (cb, params) => {
    // if (isLogging) return
    // isLogging = true
    
    try {
        const [err, res] = await uni.login()
        if (err || res.errMsg !== 'login:ok') {
            uni.$showMsg('登录失败！！')
            return
        }

		const query = {
			code: res.code,
			shareRecordId: uni.getStorageSync('shareRecordId') || ''
		}
        const loginRes = await login(query)
        
        // 统一处理存储逻辑
        store.commit('setTOken', loginRes.data.accessToken)
        uni.setStorageSync('token', loginRes.data.accessToken)
		uni.setStorageSync('tokenType', loginRes.data.tokenType)
		store.commit('setUserInfo', loginRes.data.userInfo)
		uni.setStorageSync('userInfo', loginRes.data.userInfo)
        
        // 新用户处理逻辑独立封装
        await handleNewUser(loginRes)
        
        // 使用setTimeout避免初始化与登录流程冲突
        setTimeout(() => cb?.(loginRes), 100)
    } finally {
        isLogging = false
    }
}

async function handleNewUser(loginRes) {
	// 没有默认手机型号时
	const deviceInfo = wx.getDeviceInfo()
	const model = deviceInfo.model
    if (!loginRes.data.userInfo.phoneModelId) {
        try {
            const modelRes = await setDefaultPhoneModel({
					phoneModelName: model
				})
			if (modelRes.data.phoneModelId != null) {
				store.commit('setPhoneModelId', modelRes.data.phoneModelId)
				store.commit('setPhoneModelName', modelRes.data.setPhoneModelName)
			} else {
				store.commit('setPhoneModelId', 35)
				store.commit('setPhoneModelName', '苹果 16 Pro Max')
			}

        } catch (e) {
            console.error('机型设置失败', e)
        }
    }
}

//登录
// export const userLogin = async (cb, params) => {
// 	const [err, res] = await uni.login().catch(err => err)
// 	if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！！')

// 	const query = {
// 		code: res.code,
// 		shareRecordId: uni.getStorageSync('shareRecordId') || ''
// 	}
// 	uni.removeStorageSync('shareRecordId')
// 	await login(query).then((res) => {
// 		console.log('登陆成功')
// 		store.commit('setTOken', res.data.accessToken)
// 		uni.setStorageSync('token', res.data.accessToken)
// 		uni.setStorageSync('tokenType', res.data.tokenType)
// 		store.commit('setUserInfo', res.data.userInfo)
// 		uni.setStorageSync('userInfo', res.data.userInfo)
// 		// 没有默认手机型号时
// 		const deviceInfo = wx.getDeviceInfo()
// 		const model = deviceInfo.model
// 		console.log(deviceInfo.brand, deviceInfo.model);
// 		if (!res.data.userInfo.phoneModelId) {//新用户的时候设置默认手机型号
// 			setDefaultPhoneModel({
// 				phoneModelName: model
// 			}).then(res => {
// 				if (res.data.phoneModelId != null) {
// 					store.commit('setPhoneModelId', res.data.phoneModelId)
// 					store.commit('setPhoneModelName', res.data.setPhoneModelName)
// 				} else {
// 					store.commit('setPhoneModelId', 35)
// 					store.commit('setPhoneModelName', '苹果 16 Pro Max')
// 				}

// 			})
// 		}
// 		if (cb) {
// 			cb(res)
// 		}
// 	})
// }

// 上传图片
export const uploadImage = (filePath, sucessCb, failCb) => {
	uploadFile('rest/app/userImage/create', filePath, 'image', {}, sucessCb, failCb)
}

// 上传背景图片
export const uploadStickerImage = (filePath, sucessCb, failCb) => {
	uploadFile('rest/app/stickerImage/create', filePath, 'image', {}, sucessCb, failCb)
}

// 上传文字图片
export const uploadTextImage = (filePath, formData, sucessCb, failCb) => {
	uploadFile('/rest/app/customProduct/generateWord', filePath, formData.flag,formData, sucessCb, failCb)
}

// 提交图片编辑结果
export const submitCustomImage = (filePath, formData, sucessCb, failCb) => {
	uploadFile('rest/app/customProduct/update', filePath, 'image', formData, sucessCb, failCb)
}

// 生成手机壳订单图
export const generatePhoneCaseOrder = (filePath, formData, sucessCb, failCb) => {
	uploadFile('rest/app/phoneCase/insert', filePath, 'image', formData, sucessCb, failCb)
}
// 上传文件
const uploadFile = (url, filePath, type, formData, sucessCb, failCb) => {
	const baseUrl = config.baseUrl
	const token = uni.getStorageSync('token') || ''
	const tokenType = uni.getStorageSync('tokenType') || 'Bearer'
	uni.uploadFile({
		url: baseUrl + url, // 上传文件的服务器地址
		filePath: filePath, // 要上传图片的路径
		name: type, // 文件对应的 key，服务器通过这个 key 获取文件
		header: {
			'Authorization': `${tokenType} ${token}`
		},
		formData: {
			...formData
		},
		success: (uploadFileRes) => {
			if (JSON.parse(uploadFileRes.data).code == 11) {
				uni.showToast({
					title: JSON.parse(uploadFileRes.data).msg,
					icon: 'error',
					duration: 2000
				})
			} else {
				if (sucessCb) {
					sucessCb(uploadFileRes)
				}
			}
		},
		fail: (err) => {
			console.error(err)
			if (failCb) {
				failCb()
			}
		}
	});
}

// 支付
export const payment = (data, success, fail) => {
	uni.requestPayment({
		provider: data.provider || 'wxpay',
		timeStamp: data.timeStamp || '',
		nonceStr: data.nonceStr || '',
		package: data.package || '',
		signType: data.signType || '',
		paySign: data.paySign || '',
		success(res) {
			success && success()
		},
		fail(err) {
			// uni.switchTab({
			//  url: '/pages/index/index'
			// })
			console.log('fail:' + JSON.stringify(err));
			success && fail()
		}
	});
}

export const paymentToOrder = (orderId,isDiscounts) => {
	if (isDiscounts) {
		uni.setStorageSync('toOrderPage', true)
		let timer1 = setTimeout(() => {
			clearTimeout(timer1)
			uni.switchTab({
				url: "/pages/my/my"
			})
		}, 1000)
		return
	}
	paymentOrder({
		orderId
	}).then(res => {
		let data = res.data
		payment({
			"provider": data.provider,
			"nonceStr": data.nonceStr,
			"package": data.packageStr,
			"paySign": data.paySign,
			"signType": data.signType,
			"timeStamp": data.timestamp,
		}, () => {
			uni.setStorageSync('toOrderPage', true)
			let timer1 = setTimeout(() => {
				clearTimeout(timer1)
				uni.switchTab({
					url: "/pages/my/my"
				})
			}, 1000)

		}, () => {
			uni.showToast({
				title: '你已取消支付',
				icon: 'error'
			});
			uni.setStorageSync('toOrderPage', true)
			let timer2 = setTimeout(() => {
				clearTimeout(timer2)
				uni.switchTab({
					url: "/pages/my/my"
				})
			}, 1000)
		})
	})
}

// 生成定制效果图cavas
export const drawCanvas = async (data,that) => {
	const screenWidth = uni.getWindowInfo().screenWidth
	const pixel = 750 / screenWidth
	const adapt = 0.75
	const ctx = uni.createCanvasContext('drawCanvas', that)
	ctx.fillStyle = '#fff'
	ctx.fillRect(0, 0, 1000, 1000)
	console.log('utils-drawCanvas',data);
	data.stickerImageList.sort((a, b) => {
		return a.index - b.index
	})
	// 机壳底部
	if (data.bottomMaterialUrl) {
		await drawImage(data.bottomMaterialUrl)
	}

	for (const item of data.stickerImageList) {
		await drawDecorate(item)
	}
	// 机壳顶部
	await drawImage(data.topMaterialUrl)

	ctx.draw();

	// 绘制无坐标的图片
	async function drawImage(imageurl) {
		return new Promise((resolve) => {
			uni.getImageInfo({
				src: imageurl,
				success: (res) => {
					ctx.drawImage(res.path, 0, 0, screenWidth, screenWidth);
					// ctx.draw();
					resolve()
				},
				fail: () => {
					resolve()
				}
			});
		})
	}

	// 绘制贴纸
	async function drawDecorate(data, bg) {
		return new Promise((resolve) => {
			uni.getImageInfo({ //  获取图片信息
				src: data.imageUrl,
				success: (res) => {
					let height = data.height * adapt / pixel //  计算图片的宽高
					let width = data.width * adapt / pixel
					let x = data.x * adapt / pixel //  计算图片的位置
					let y = data.y * adapt / pixel
					let scaleX = data.overturn ? -1 * data.scaleX : data.scaleX //  计算图片的缩放比例
					let scaleY = data.scaleY
					let rotate = data.overturn ? -1 * data.rotationAngle : data.rotationAngle //  计算图片的旋转角度

					ctx.save(); //  保存画布状态 因为图片的旋转和缩放是相对于画布的原点进行的，所以需要保存画布状态以便于后续恢复
					ctx.translate(x, y) //  平移画布
					ctx.scale(scaleX, scaleY)
					ctx.translate((width / scaleX - width) / 2, (height / scaleY - //  平移画布
						height) / 2)
					ctx.translate(width / 2, height / 2) //  平移画布
					// 将画布旋转
					ctx.rotate(rotate * (Math.PI / 180)) //  旋转画布
					ctx.translate(-width / 2, -height / 2) //  平移画布
					ctx.drawImage(res.path, 0, 0, width, height) //  绘制图片
					ctx.restore(); //  恢复画布状态 为了下一次绘制原点不变（0,0）
					resolve() //  解析Promise
				}
			});
		})

	}
}
// 生成Canvas图片
export const generateCanvas = (data, delay,that) => {
	return new Promise(resolve => {
		drawCanvas(data,that); // 先绘制元素
		// 使用 setTimeout 来确保绘制完成后再导出图片（因为 drawImage 是异步的）
		setTimeout(() => {
			uni.canvasToTempFilePath({
				canvasId: 'drawCanvas',
				success: (res) => {
					console.log(res);
					resolve(res.tempFilePath)
				},
				fail: (err) => {
					console.error('导出图片失败', err);
				}
			},that);
		}, delay); // 这里设置了1秒的延迟，实际使用时可能需要根据绘制内容的复杂度来调整
	})

}

